// 640. 求解方程

/**
 * @param {string} equation
 * @return {string}
 */
var solveEquation = function (equation) {
    let result = 0;
    let x = 0;
    let array = [];
    let tempStr = "";
    equation = equation.split("=");

    for (let i = 0; i < equation[0].length; i++) {
        let p = equation[0][i];
        if (i === 0 && p === '-') {
            tempStr += p;
            continue;
        }
        if (p === "+" || p === "-") {
            array.push(tempStr);
            tempStr = "";
        }

        tempStr += p;

        if (i === equation[0].length - 1) {
            array.push(tempStr);
            tempStr = "";
        }
    }

    for (let i = 0; i < equation[1].length; i++) {
        let p = equation[1][i];
        if (i === 0) {
            if (p === '-') {
                tempStr = '+';
                continue;
            }
            p = '-' + p;
        }
        if (p === "+" || p === "-") {
            p = p === "+" ? '-' : '+';
            array.push(tempStr);
            tempStr = "";
        }

        tempStr += p;

        if (i === equation[1].length - 1) {
            array.push(tempStr);
            tempStr = "";
        }
    }

    array.forEach((p) => {
        let temp = 0;
        let length = p.length;
        if (p[length - 1] === "x") {
            let xNum = Number(p.slice(0, length - 1));
            switch (p) {
                case 'x':
                case '+x':
                    xNum = 1;
                    break;
                case "-x":
                    xNum = -1;
                    break;
                default:
                    break;
            }
            x += xNum;
            // console.log(xNum, "xNum");
        } else {
            temp = Number(p);
            result += temp;
        }
    });

    console.log(array, result, x);

    if (x === 0 && result !== 0) {
        return "No solution";
    }

    switch (x) {
        case 0:
            return "Infinite solutions";
            break;
        default:
            return `x=${-(result / x)}`;
            break;
    }
};

console.log(solveEquation("x+5-3+x=6+x-2"), "x=2");
// console.log(solveEquation("2x=x"), "x=0");
// console.log(solveEquation("x=x+2"), "No solution");
// console.log(solveEquation("x=x"), "Infinite solutions");
console.log(solveEquation("-x=-1"), "x=1");

